<?php
namespace app\admin\controller\integral;
use app\admin\model\Admin;
use app\admin\model\AuthDepartment;
use app\admin\model\Department;
use app\admin\model\finance\extract\Week;
use app\admin\model\integral\Stat;
use app\common\controller\Backend;
use fast\Office;
use think\Db;
use think\Loader;
use think\Session;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Bookmanager extends Backend
{
    
    /**
     * Manager模型对象
     * @var \app\admin\model\integral\Bookstore
     * * @var \app\admin\model\integral\Teachertel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->BookManagerModel = new \app\admin\model\integral\Bookmanager;
        $this->model = new \app\admin\model\integral\Teachertel;

    }
    
    /**
     * 查看
     */
    public function index($ids=null)
    {
        //当前是否为关联查询
//        $this->relationSearch = true;
        $BookManagerRow = $this->BookManagerModel->get(['week_id'=>$ids]);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->field('count(userid) as number,id,name,tel,userid,week_id')
                    ->where('week_id','=',$ids)
                    ->where($where)
                    ->order($sort, $order)
                    ->group('userid')
                    ->count();
            $list = $this->model
                    ->field('count(userid) as number,id,name,tel,userid,week_id')
                    ->where($where)
                    ->where('week_id','=',$ids)
                    ->order($sort, $order)
                    ->group('userid')
                    ->limit($offset, $limit)
                    ->select();
            $TotalScore = 0;
            foreach ($list as $row) {
                if($BookManagerRow)
                {
                    $number = $row['number'] / 2;
                    if($number < $BookManagerRow['photo_number'] || $number < $BookManagerRow['follow'] )
                    {
                        $row['integral'] = $row['number'] * 3;
                    }else{
                        $row['integral'] = 0;
                    }
                }
				$row['week_id_text'] = Week::getName($row['week_id']);
				$row['userid_text'] = Admin::userName($row['userid']);
            }
            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign("ids", $ids);

        $BookManagerRow  = $BookManagerRow ? true : false;
        $this->view->assign("BookManagerRow", $BookManagerRow);
        return $this->view->fetch();
    }

    /**
     * 生成图书经理积分统计
     * @param null $ids
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function generate($ids=null)
    {
        if(!$ids) return $this->error('请选取要生成的周次');
        $name = Week::field('group_concat(name) as ids ')->where('id','in',$ids)->select();
        $concatid = Week::field('group_concat(id) as ids ')->where('name','in',$name[0]['ids'])->select();

        if($this->request->request('params') == 'export')
        {
            if(!$this->autnGenerate($name[0]['ids'])) $this->error('请生成你选择的数据，在执行导出！');
          return $this->success("<script>var newWeb=window.open('_blank');newWeb.location = 'bookmanager/export?names={$name[0]['ids']}';</script>");
        }

        if($this->request->request('params') == 'export')
        {
            return $this->success();
        }
        return $this->success('还不能生成数据！在做任务单');
        if($this->request->request('params') == 'product')
        {
            //生成数据
            $stat = new Stat;
            $list = [];
            foreach (explode(',',$concatid[0]['ids']) as $value)
            {
                if(!Stat::where(['week_id'=>$value])->select()->toArray())
                {
                    $row = Week::get($value);
                    $res = Db::query("select count(*) as number from hdyj_admin as a left join `hdyj_auth_group_access` as b ON a.userid=b.userid where a.department like '%".$row['department']."%' and b.`group_id`=20");
                    $BookManager = \app\admin\model\integral\Bookmanager::where(['week_id'=>$value])->select()->toArray();
                    $teacher = \app\admin\model\integral\Teachertel::where('week_id',$value)->count();
                    $follow = $BookManager ? $BookManager[0]['follow'] : 0;
                    $photo = $BookManager ? $BookManager[0]['photo_number'] : 0;
                    $list[] = [
                        'week_id'=>$value,
                        'department'=>$row['department'],
                        'department_text'=>$row['department_text'],
                        'users'=> $res[0]['number'],//图书经理人
                        'teacher'=>$teacher,//全名老师数量	  建立老师联系方式数量
                        'follow'=>$follow,//教改论坛加关注数量
                        'photo'=>$photo,//照片数量
                        'follow_s'=>($follow > 0 && $teacher > 0) ? round($follow / $teacher,2) : 0 , // 公众号关注数量除以老师通联方式
                        'photo_s'=>($follow > 0 && $teacher > 0) ?  round($photo / $teacher,2): 0, // 照片数量除以老师通联方式
                    ];
                }

            }
            if(!$list) return $this->error('没有可以生成新的数据！');

            $stat->saveAll($list);

            return $this->success();
        }

    }

    public function export($names)
    {
        $excel = new Office();
        //设置表头：//'本周计划任务学校数量','本周完成计划内任务学校数量','本周完成任务计划外学校数量','完成比率',
        $head = ['序号', '分公司', '图书经理人', '本周计划任务学校数量','本周完成计划内任务学校数量','本周完成任务计划外学校数量','完成比率','建立老师联系方式数量','教改论坛加关注数量','加关注比例','照片数量','照片比率'];
        //数据中对应的字段，用于读取相应数据：
        $keys = ['id', 'department_text', 'users','school_number','school_within','school_abroad','complete', 'teacher', 'teacher','follow','follow_s','photo','photo_s'];

        foreach (explode(',',$names) as $key=>$value) {
            $concatid = Week::field('group_concat(id) as ids ')->where('name', 'in', $value)->select();
            $list[] = Stat::where('week_id', 'in', $concatid[0]['ids'])->select()->toArray();
            $sheelTitle[] = $value;
        }
        $excel->outdata('图书送样完成情况统计表', $list, $head, $keys,$sheelTitle);
        exit;
    }

    /**
     * 查看详情  送样完成情况
     * @param null $ids
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function stat($ids=null)
    {
        $row = Week::get($ids);
        $ids = Week::where(array('start_time'=>$row['start_time'],'end_time'=>$row['end_time']))->field('group_concat(id) as ids ')->select();
        $list = Stat::where('week_id','in',$ids[0]['ids'])->select()->toArray();
        if(!$list) return $this->error('请生成你选中的数据在进行查看!');
        $this->view->assign("row", $row);
        $this->view->assign("list", $list);
        return $this->view->fetch();
    }

    //验证是否生产数据
    public function autnGenerate($name=null)
    {
        //请先生成数据
        $week =  count(explode(',',$name));
        $b=0;
        foreach (explode(',',$name) as $key=>$value) {
            $concatid = Week::field('group_concat(id) as ids ')->where('name', 'in', $value)->select();
            if(Stat::where('week_id', 'in', $concatid[0]['ids'])->select()->toArray()) $b++;
        }
        if($b != $week)
        {
            return false;
        }
        return true;
    }

    /**
     * 添加
     */
    public function add($ids=null)
    {
        $row = $this->BookManagerModel->get(['week_id'=>$ids]);
        if ($row) $this->error(__('已经添加过了，不要重复添加，请关闭页面重新打开。'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->BookManagerModel));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->BookManagerModel->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->BookManagerModel->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function bookmanageredit($ids = NULL)
    {
        $row = $this->BookManagerModel->get(['week_id'=>$ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->BookManagerModel)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }




    public function import($ids=null)
    {
        $admin = Session::get('admin');
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                    $row['week_id'] = $ids;
                    $row['userid'] = $admin['id'];
                }
            }
            if($this->importValidate($row))
            {
                $insert[] = $row;
            }
        }
        if (!$insert) {
            $this->error(__('请上传有效的数据！'));
        }
        try {
            $this->model->saveAll($insert);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success();
    }

    /**
     * 验证数据
     * @param $row
     * @return null
     */
    protected function importValidate($row)
    {
        if (!preg_match("/^1[3456789]{1}\d{9}$/", $row['tel'])) {
            $row['tel'] = null;
        }
        if ($row['name'] && $row['week_id'] && $row['tel'] && $row['role'] && $row['userid']) {
            if($row['name'] != '老师' && mb_strlen($row['name']) >= 2 && !strpos($row['name'],'老师')){
                return true;
            }
        }
        return false;
    }
}
